package com.gitbl.webchat.server;

import com.gitbl.webchat.db.DbHelper;
import com.gitbl.webchat.message.RoomMessage;
import com.gitbl.webchat.message.RoomsNodeMessage;
import com.gitbl.webchat.service.RoomService;
import com.gitbl.webchat.utils.RedisHelper;

import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.config.annotation.Service;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import redis.clients.jedis.*;
import redis.clients.jedis.commands.ProtocolCommand;

import java.util.*;

import static redis.clients.jedis.Protocol.CHARSET;

@Service(version = "1.0.0")
public class RoomServer implements RoomService {

    Thread nodereflash;
    List<RoomsNodeMessage> nodes;
    Random random;
    DbHelper db;
    synchronized void setNodes(List<RoomsNodeMessage> nodes){
        this.nodes = nodes;
    }
    synchronized List<RoomsNodeMessage> getNodes(){
        return this.nodes;
    }
    public RoomServer(){
        String shosts = System.getProperty("session.hosts");
        if(shosts==null||shosts.equals(""))
            shosts="127.0.0.1:6379";
        String[] hostsadd= shosts.split(",");
        db = new DbHelper(hostsadd);

        random = new Random();
        nodes = new ArrayList<>();

        nodereflash = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        List<RoomsNodeMessage> roomnodes = db.getAllNodes();
                        setNodes(roomnodes);
                    }catch (Exception ex){

                    }
                    try {
                        Thread.sleep(6000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        nodereflash.start();

    }

    @Value("${dubbo.application.name}")
    private String serviceName;

    public boolean ping() {
        return true;
    }

    public String address() {
        return null;
    }

    @Override
    public RoomMessage getRoom(String id) {
        return db.getRoom(id);
    }

    @Override
    public RoomMessage createRoom(String t,String u) {
        RoomsNodeMessage node = getRandomNode();
        if(node==null){
            return null;
        }
        HashMap<String,Object> par = new HashMap<>();
        par.put("title",t.replaceAll("\\.",""));
        par.put("owner",u);
        String resp = sendPost(node.getApiAddress(),par);

        return JSONObject.parseObject(resp,RoomMessage.class);
    }

    private RoomsNodeMessage getRandomNode() {
        List<RoomsNodeMessage> nds = getNodes();
        if(nds==null||nds.size()==0)
            return null;
        return nds.get(random.nextInt(nds.size()));
    }

    @Override
    public List<RoomMessage> queryRooms(String title) {
        return db.queryLessRoom(title);
    }

    @Override
    public void closeRoom(int i) {

    }

    @Override
    public void registNode(RoomsNodeMessage roomsNodeMessage) {

    }



    String sendPost(String url, Map<String,Object> params) {
        String response = null;
        System.out.println(url);
        System.out.println(params);
        try {
            List<BasicNameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<>(params.size());
                for (String key : params.keySet()) {
                    pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
                }
            }
            CloseableHttpClient httpclient = null;
            CloseableHttpResponse httpresponse = null;
            try {
                httpclient = HttpClients.createDefault();
                HttpPost httppost = new HttpPost(url);
                // StringEntity stringentity = new StringEntity(data);
                if (pairs != null && pairs.size() > 0) {
                    httppost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
                }
                httpresponse = httpclient.execute(httppost);
                response = EntityUtils
                        .toString(httpresponse.getEntity());
                System.out.println(response);
            } finally {
                if (httpclient != null) {
                    httpclient.close();
                }
                if (httpresponse != null) {
                    httpresponse.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }
}
